package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import db.oracle.OracleConnMgr;
import dto.MemberDTO;

public class MemberDAO {
	public boolean login(String userid, String userpw){
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		boolean ret = false;
		String insertQuery = 
			"select f_member_pw from t_member " +
			"where f_member_id = ?";
		String pw_original = null;
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(insertQuery);
			pstmt.setString(1, userid);
			rs = pstmt.executeQuery();
			
			if(rs.next())
				pw_original = rs.getString(1);
			
			if(pw_original.equals(userpw))
				ret = true;
						
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				mgr.close(conn, pstmt, rs);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return ret;
	}
	public String register(MemberDTO mdto){
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		int ret = 0;
		String insertQuery = 
			"INSERT INTO member (f_member_id, f_member_pw, f_member_phon, " +
			"f_member_grp, f_member_twit, f_member_faceb, f_member_mail, f_member_auth )" +
			" values(?,?,?,?,?,?,?,?)";
		int auth = AuthNum();
		
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(insertQuery);
			pstmt.setString(1, mdto.getMemID());
			pstmt.setString(2, mdto.getMemPW());
			pstmt.setString(3, mdto.getMemPhone());
			pstmt.setInt(4, mdto.getMemGroup());
			pstmt.setString(5, mdto.getMemTwit());
			pstmt.setString(6, mdto.getMemFaceb());
			pstmt.setString(7, mdto.getMemMail());
			pstmt.setString(8, "" + auth);
			//pstmt.setString(9, );
			ret = pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				mgr.close(conn, pstmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		sendMail(mdto.getMemMail(), auth);		
		
		if(ret == 0)
			return null;
		else
			return mdto.getMemID();
	}
	
	private int AuthNum(){
		int tmp = (int)(Math.random() * 10000000) + 10000000;
		
		return tmp;
	}
	
	private void sendMail(String mailto, int auth){
		SimpleEmail email = new SimpleEmail(); // 선언을 한다
		String msg = "감사합니다.\n아래의 인증번호를 입력하시면 가입 완료됩니다.\n\n"+auth;
		
		try {
			email.setCharset("UTF-8");     // 인코딩을 설정한다.
			email.setHostName("mail.ssu.ac.kr");
			email.setFrom("engineerj@ssu.ac.kr", "admin");
			email.setAuthentication("engineerj@ssu.ac.kr", "92837465"); //SMTP 인증이 필요할 경우(없으면 지워버린다.)
			email.addTo(mailto + "@ssu.ac.kr", mailto); //받는사람
			email.setSubject("모바일 컴퓨터학부 커뮤니티 인증번호 입니다."); //메일 제목
			email.setMsg(msg); //메일 내용
			email.send(); //메일 발송
		} catch (EmailException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //보내는 사람
	}

	public boolean authorize(String mID, String aNum){
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String insertQuery = 
			"select f_member_auth from t_member " +
			"where f_member_id = ?";
		String dbsavednum = null;
		
		boolean result = false;
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(insertQuery);
			pstmt.setString(1, mID);
			rs = pstmt.executeQuery();
			
			if(rs.next())
				dbsavednum = rs.getString(1);
			
			if(dbsavednum.equals(aNum)){
				insertQuery = "update t_member set f_member_auth = " +
						"'authorized' where f_member_id = ?";
				pstmt = conn.prepareStatement(insertQuery);
				pstmt.setString(1, mID);
				int tmp = pstmt.executeUpdate();
				
				if(tmp != 0)
					result = true;
				
			}
			
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				mgr.close(conn, pstmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	public boolean authorized(String mID){
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String insertQuery = 
			"select f_member_auth from t_member " +
			"where f_member_id = ?";
		String authok = null;
		
		boolean result = false;
		
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(insertQuery);
			pstmt.setString(1, mID);
			rs = pstmt.executeQuery();
			
			if(rs.next())
				authok = rs.getString(1);
			
			if(authok.equals("authorized"))
				result = true;			
			
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				mgr.close(conn, pstmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
	
	public int UpdateUserInfo(MemberDTO mdto){
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		String updateQuery = "UPDATE t_member SET" +
				"f_member_pw = ?," +
				"f_member_phon = ?," +
				"f_member_grp = ?," +
				"f_member_twit = ?," +
				"f_member_faceb = ? WHERE" +
				"f_member_id = ?";
		int ret = 0;
		
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(updateQuery);
			pstmt.setString(1, mdto.getMemPW());
			pstmt.setString(2, mdto.getMemPhone());
			pstmt.setInt(3, mdto.getMemGroup());
			pstmt.setString(4, mdto.getMemTwit());
			pstmt.setString(5, mdto.getMemFaceb());
			pstmt.setString(6, mdto.getMemID());
			ret = pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				mgr.close(conn, pstmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return ret;
	}
	public int DeleteUserInfo(String userid){
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		String updateQuery = 
			"DELETE FROM t_member WHERE f_member_id = ?";
		int ret = 0;
		
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(updateQuery);
			pstmt.setString(1, userid);
			ret = pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				mgr.close(conn, pstmt);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return ret;
	}
	
	public MemberDTO ReadUserInfo(String userid) throws SQLException, Exception {
		MemberDTO dto = new MemberDTO();
		OracleConnMgr mgr = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String readQuery = 
			"SELECT * FROM t_member WHERE f_member_id = ?";
		
		try {
			mgr = OracleConnMgr.getInstance();
			conn = mgr.getConnection();
			pstmt = conn.prepareStatement(readQuery);
			pstmt.setString(1, userid);
			rs = pstmt.executeQuery();
			
			if (rs.next()) {
				dto.setMemID(userid);
				dto.setMemPW(rs.getString("f_member_pw"));
				dto.setMemPhone(rs.getString("f_member_phon"));
				dto.setMemGroup(rs.getInt("f_member_pw"));
				dto.setMemTwit(rs.getString("f_member_twit"));
				dto.setMemFaceb(rs.getString("f_member_faceb"));
				dto.setMemMail(rs.getString("f_member_mail"));
				dto.setMemAuthinfo(rs.getString("f_member_auth"));
				dto.setMemImagePath(rs.getString("f_member_pw"));
			}
		} catch (SQLException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			mgr.close(conn, pstmt, rs);
		}
		
		return dto;
	}
	
}
